package com.glsc.ngateway.platform.controller.feign;

import com.glsc.ngateway.common.api.common.dto.PageDataResult;
import com.glsc.ngateway.common.api.common.dto.PageDto;
import com.glsc.ngateway.common.api.common.dto.PageQueryParamDto;
import com.glsc.ngateway.common.api.ldap.dto.LdapEhrDeptDto;
import com.glsc.ngateway.common.api.ldap.dto.LdapEhrDeptSearchDto;
import com.glsc.ngateway.common.api.ldap.feign.IFeignLdapService;
import com.glsc.ngateway.common.api.ldap.resp.LdapResponse;
import com.glsc.ngateway.common.api.oaflow.dto.OaRequestLogResp;
import com.glsc.ngateway.common.api.oaflow.dto.oaflow.WorkflowBaseDto;
import com.glsc.ngateway.common.api.oaflow.dto.oaflow.WorkflowBaseQueryParamDto;
import com.glsc.ngateway.common.api.oaflow.dto.oaform.FormDictInfoDto;
import com.glsc.ngateway.common.api.oaflow.dto.oaform.FormInfoDto;
import com.glsc.ngateway.common.api.oaflow.dto.xirtrade.TOaFlowXirTradeBaseInfoDto;
import com.glsc.ngateway.common.api.oaflow.dto.xirtrade.TOaFlowXirTradeInfoDeleteParamDto;
import com.glsc.ngateway.common.api.oaflow.dto.xirtrade.TOaFlowXirTradeInfoSearchParamDto;
import com.glsc.ngateway.common.api.oaflow.feign.IFeignOaFlowService;
import com.glsc.ngateway.common.api.oaflow.resp.CommonResponse;
import com.glsc.ngateway.common.api.oaflow.resp.OaflowResponse;
import com.glsc.ngateway.common.api.platform.dto.user.PlatformUserDto;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.common.base.exception.PlatformException;
import com.glsc.ngateway.platform.utils.RequestTool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.glsc.ngateway.common.api.common.enums.DictConstant.ROLE_OPEARATOR;

/**
 * @author zzp
 * @date 2022/12/9
 * 自研流程调用接口
 */
@RequestMapping("/oaflow")
@Api(value = "自研Oaflow调用接口", tags = {"自研Oaflow调用接口"})
@RestController
public class OaflowFeignController {

    private static final Logger logger = LoggerFactory.getLogger(OaflowFeignController.class);

    @Autowired
    private IFeignOaFlowService oaFlowService;

    @Resource
    private RequestTool requestTool;

    @Resource
    private IFeignLdapService iFeignLdapService;

    @RequestMapping(method = RequestMethod.GET, value = "/getRequestLogList")
    public OaRequestLogResp getRequestLogList(@RequestParam("requestId") Integer requestId) {
        PlatformUserDto user = requestTool.getUserFromRequest();
        CommonResponse<OaRequestLogResp> resp = oaFlowService.getRequestLogList(requestId, new ArrayList<>(user.getRoles()));
        return resp.getData();
    }

    /**
     * 衡泰指令同步记录功能
     */
    @PostMapping("/xir/search")
    @ApiOperation(value = "查询同步记录", notes = "查询同步记录")
    public PlatformResponse<PageDto<TOaFlowXirTradeBaseInfoDto>> query(@RequestBody PageQueryParamDto<TOaFlowXirTradeInfoSearchParamDto> queryParam) throws Exception {
        TOaFlowXirTradeInfoSearchParamDto param = queryParam.getParam();
        if (Strings.isNotBlank(param.getSettleDateMin())) {
            param.setSettleDateMin(param.getSettleDateMin() + " 00:00:00");
        }
        if (Strings.isNotBlank(param.getSettleDateMax())) {
            param.setSettleDateMax(param.getSettleDateMax() + " 23:59:59");
        }
        String operator = requestTool.getAccountFromRequest();
        PlatformUserDto user = requestTool.getUserFromRequest();
        Set<String> roleNames = new HashSet<>(user.getRoles());
        if (Strings.isBlank(operator)) {
            return PlatformResponse.successData(PageDto.empty());
        } else if (!"itadmin".equals(operator) && !"admin".equals(operator) && !roleNames.contains(ROLE_OPEARATOR) ) {
            LdapEhrDeptDto dept = iFeignLdapService.getDepByAccount(operator).getData();
            if (Objects.isNull(dept)) {
                throw PlatformException.error("未找到部门信息");
            }
            queryParam.getParam().getDeptTitleList().add(dept.getDtitle());
            if ("一级部门".equals(dept.getDepgrade())) {
                //找所有下级部门
                LdapResponse<List<LdapEhrDeptDto>> resp = iFeignLdapService.getDepartmentList(LdapEhrDeptSearchDto.builder().aTitle(dept.getDtitle()).build());
                if (CollectionUtils.isNotEmpty(resp.getData())) {
                    queryParam.getParam().getDeptTitleList().addAll(resp.getData().stream().map(LdapEhrDeptDto::getDtitle).collect(Collectors.toList()));
                }
            }
        }
        OaflowResponse<PageDto<TOaFlowXirTradeBaseInfoDto>> oaResp = oaFlowService.query(queryParam);
        PageDto<TOaFlowXirTradeBaseInfoDto> respData = oaResp.getData();
        if (Objects.nonNull(respData) && CollectionUtils.isNotEmpty(respData.getContent())) {
            DecimalFormat decimalFormat = new DecimalFormat("#,##0.##");
            respData.getContent().forEach(tradeInfo -> {
                //交易员流程发起人拼接
                tradeInfo.setDealerAndApplicant((Strings.isBlank(tradeInfo.getDealer()) ? "空" : tradeInfo.getDealer()) + "/" +
                        (Strings.isBlank(tradeInfo.getApplicant()) ? "空" : tradeInfo.getApplicant()));
                //利率变百分比
                tradeInfo.setSettleFeeRateStr(Objects.isNull(tradeInfo.getSettleFeeRate()) ? null : tradeInfo.getSettleFeeRate().multiply(new BigDecimal("100")).stripTrailingZeros() + "%");
                //金额格式化
                tradeInfo.setChangeAmountStr(Objects.isNull(tradeInfo.getChangeAmount()) ? null : decimalFormat.format(tradeInfo.getChangeAmount()));
            });
        }
        return oaResp.isSuccess() ? PlatformResponse.successData(respData) : PlatformResponse.failed();
    }

    @PostMapping("/xir/delete")
    @ApiOperation(value = "删除记录", notes = "删除记录")
    public PlatformResponse<?> delete(@RequestBody TOaFlowXirTradeInfoDeleteParamDto param) {
        OaflowResponse<Void> oaResp = oaFlowService.delete(param);
        return oaResp.isSuccess() ? PlatformResponse.success() : PlatformResponse.failed();
    }

    @GetMapping("/xir/syncXirTrade")
    public PlatformResponse<?> syncXirTrade(@RequestParam(value = "date", required = false) String date,
                                            @RequestParam(value = "unPushFlow", required = false) boolean unPushFlow) {
        OaflowResponse<Void> oaResp = oaFlowService.syncXirTrade(date, unPushFlow);
        return oaResp.isSuccess() ? PlatformResponse.successMsg(oaResp.getMsg()) : PlatformResponse.failedMsg(oaResp.getMsg());
    }

    @ApiOperation(value = "产品系统查询OA资管流程Workflow清单", notes = "产品系统查询OA资管流程Workflow清单")
    @GetMapping("/oaWorkflowDef/listpage")
    public PlatformResponse<PageDto<WorkflowBaseDto>> listWorkFlowPage(@ApiParam(value = "OA流程名称") @RequestParam(required = false) String workflowname,
                                                                       @ApiParam(value = "页码从1开始") @RequestParam(required = false) Integer pageNo,
                                                                       @ApiParam(value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize
    ) {
        CommonResponse<PageDto<WorkflowBaseDto>> resp = oaFlowService.pageWorkflowBase(
                PageQueryParamDto.<WorkflowBaseQueryParamDto>builder()
                        .pageNo(pageNo)
                        .pageSize(pageSize)
                        .param(WorkflowBaseQueryParamDto.builder()
                                .workflowname(workflowname)
                                .build())
                        .sorter(List.of(new PageQueryParamDto.Sort("id", PageQueryParamDto.Sort.ORDER_DESC)))
                        .build());
        return PlatformResponse.successData(resp == null || resp.getData() == null ? PageDto.empty() : resp.getData());
    }

    @GetMapping("getWorkFlowOaFormInfo")
    public PlatformResponse<List<FormInfoDto>> getWorkFlowOaFormInfo(@RequestParam("workflowId") String workflowId) {
        logger.info("查询OA流程表单信息,workflowId：{}", workflowId);
        CommonResponse<List<FormInfoDto>> resp = oaFlowService.getWorkFlowOaFormInfo(workflowId);
        return PlatformResponse.successData(resp == null || resp.getData() == null ? Collections.EMPTY_LIST : resp.getData());
    }

    @GetMapping(value = "getWorkFlowOaFormDictInfo")
    public PlatformResponse<List<FormDictInfoDto>> getWorkFlowOaFormDictInfo(@RequestParam("workflowId") String workflowId) {
        logger.info("查询OA流程表单字典信息,workflowId：{}", workflowId);
        CommonResponse<List<FormDictInfoDto>> resp = oaFlowService.getWorkFlowOaFormDictInfo(workflowId);
        return PlatformResponse.successData(resp == null || resp.getData() == null ? Collections.EMPTY_LIST : resp.getData());
    }

    /*
     * 检查网关返回数据是否正常
     * */
    private boolean validGatewayResponse(PageDataResult ret) {
        if (null == ret) {
            logger.info("接口返回为空");
            throw PlatformException.error("接口返回为空");
        } else if (ret.getCode() != 0 && ret.getCode() != 18) {//分页返回18是正常
            String errMsg = "接口返回异常，错误码=" + ret.getCode();
            logger.info(errMsg);
            throw PlatformException.error(errMsg);
        } else {
            logger.info("接口返回正常，返回信息=" + ret);
            return true;
        }
    }
}
